#!/usr/bin/env bash
#
# Delete the "guest" default user and replace it with a Zulip user
# with a real password
set -e
set -x

if [ "$EUID" -eq 0 ]; then
    rabbitmqctl=(rabbitmqctl)
else
    rabbitmqctl=(sudo rabbitmqctl)
fi

if [ -n "$RABBITMQ_NODE" ]; then
    rabbitmqctl+=(-n "$RABBITMQ_NODE")
fi
RABBITMQ_USERNAME=$("$(dirname "$0")/../get-django-setting" RABBITMQ_USERNAME)
RABBITMQ_PASSWORD=$("$(dirname "$0")/../get-django-setting" RABBITMQ_PASSWORD)

# Wait for RabbitMQ to start up
try_ping() {
    # `rabbitmqctl ping` requires 3.7.6 or newer
    out="$("${rabbitmqctl[@]}" eval 'net_adm:ping(node()).')" && [ "$out" = 'pong' ]
}
retries=9
while ! try_ping 2>/dev/null; do
    sleep 1
    if ! ((retries -= 1)); then
        try_ping
        break
    fi
done

"${rabbitmqctl[@]}" delete_user "$RABBITMQ_USERNAME" || true
"${rabbitmqctl[@]}" delete_user zulip || true
"${rabbitmqctl[@]}" delete_user guest || true
"${rabbitmqctl[@]}" add_user "$RABBITMQ_USERNAME" "$RABBITMQ_PASSWORD"
"${rabbitmqctl[@]}" set_user_tags "$RABBITMQ_USERNAME" administrator
"${rabbitmqctl[@]}" set_permissions -p / "$RABBITMQ_USERNAME" '.*' '.*' '.*'
